from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from enums.WidgetType import WidgetType
from PySide6.QtWidgets import QLabel, QComboBox, QVBoxLayout, QWidget
from ..ScriptInput import ScriptInput
from enums.KeyboardInputType import KeyboardInputType
from enums.ZhKeyboardInputType import ZhKeyboardInputType
import pyautogui


class InputKeyboard(ScriptWidget):
    def __init__(self, initType=None):
        super().__init__(WidgetType.INPUT_KEYBOARD)

        self.initType = initType

        self.labTitle = QLabel('按键:', self)
        self.labTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        self.comInputType = QComboBox(self)
        self.comInputType.addItems(ZhKeyboardInputType.values())
        self.comInputType.setCurrentIndex(0)
        self.addWidget(self.comInputType)

        self.inputKeys = ScriptInput(self, '按键', 16, 'string')
        self.addWidget(self.inputKeys)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        self.newLine()

        self.labInputHint = QLabel('输入提示: 请输入键盘按键对应值, 以,分割', self)
        self.labInputHint.setFixedSize(self.width(), self.lineHeight)
        self.addWidget(self.labInputHint)

    @property
    def data(self):
        text = self.inputKeys.text.replace(' ', '')
        if len(text) == 0:
            return self.error('请输入按键')

        keys = text.split(',')
        for key in keys:
            if key not in pyautogui.KEY_NAMES:
                return self.error('按键错误, ' + key)

        zhType = ZhKeyboardInputType(self.comInputType.currentText())
        inputType = KeyboardInputType[zhType.name].value
        return {
            "type": self.type.value,
            'input_type': inputType,
            'keys': keys,
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.setData(data)
        self.comInputType.setCurrentText(ZhKeyboardInputType[data['input_type'].upper()].value)
        self.inputKeys.text = ','.join(data['keys'])
